
{% extends "amdy_base.html" %}
{% load static %}
{% comment %} 额外引用的css文件 {% endcomment %}
{% block extcss %}
<link rel="stylesheet" href="{% static "css/demo.css" %}" type="text/css">
<link rel="stylesheet" href="{% static "css/filemanage.css" %}" type="text/css">
<link rel="stylesheet" href="{% static "css/metroStyle.css" %}" type="text/css">
<link rel="stylesheet" href="{% static "css/bookeditor.css" %}" type="text/css">
<link rel="stylesheet" href="{% static "plugins/font-awesome/css/font-awesome.css" %}" type="text/css">
<link rel="stylesheet" href="{% static "plugins/bootstrap/css/bootstrap.css" %}" type="text/css">
<link rel="stylesheet" href="{% static "plugins/katex/katex.css" %}" type="text/css">
<link rel="stylesheet" href="{% static "plugins/codemirror/lib/codemirror.css" %}" type="text/css">
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.0.0/styles/default.min.css">
<script type="text/javascript" src="{% static "js/jquery-1.4.4.min.js" %}"></script>
<script type="text/javascript" src="{% static "js/jquery.ztree.core.js" %}"></script>
<script type="text/javascript" src="{% static "js/jquery.ztree.excheck.js" %}"></script>
<script type="text/javascript" src="{% static "js/jquery.ztree.exedit.js" %}"></script>
<script>
    var firstJQuery = jQuery.noConflict(true);
</script>
<script type="text/javascript" src="{% static "js/marked.js" %}"></script>
<script type="text/javascript" src="{% static "js/bookeditor.js" %}"></script>
<!--markdown需要用到的jquery-->
<script type="text/javascript" src="{% static "plugins/jquery.min.js" %}"></script>
<script type="text/javascript" src="{% static "plugins/bootstrap/js/bootstrap.js" %}"></script>
<script type="text/javascript" src="{% static "plugins/katex/katex.js" %}"></script>
<script type="text/javascript" src="{% static "plugins/prettify.min.js" %}"></script>
<script type="text/javascript" src="{% static "plugins/codemirror/lib/codemirror.js" %}"></script>
<script type="text/javascript" src="{% static "plugins/codemirror/addon/mode/overlay.js" %}"></script>
<script type="text/javascript" src="{% static "plugins/codemirror/mode/markdown/markdown.js" %}"></script>
<script type="text/javascript" src="{% static "plugins/codemirror/mode/gfm/gfm.js" %}"></script>
<script type="text/javascript" src="{% static "plugins/marked/marked.js" %}"></script>
<script type="text/javascript" src="{% static "plugins/mousetrap/mousetrap.js" %}"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.0.0/highlight.min.js"></script>
<script>hljs.highlightAll();</script>
{% endblock extcss %}
{% comment %} 标题 {% endcomment %}
{% block title %}
<TITLE>文字管理系统</TITLE>
{% endblock title %}
{% comment %} 菜单栏 {% endcomment %}
{% block topbar %}
    {% comment %} {% include "amdy_model.html" with model_type="topbar" title="文件管理" name=user.nickname avatarSrc=user.icon %} {% endcomment %}
{% endblock topbar %}

{% block drawer %}
<!--
<div class="content_wrap">
    <div class="zTreeDemoBackground left">
        <ul id="treeDemo" class="ztree"></ul>
    </div>
</div>
-->
<ul id="treeDemo" class="ztree"></ul>
{% endblock drawer %}

{% block mainlay %}

    <form action="{% url 'FileManage:api/uploadFile' %}" method="post"  id="editView" style="display:none" enctype="multipart/form-data">
        {% csrf_token %}
        <mdui-button-icon id="addParent" type="button" variant="text" icon="create_new_folder" style="height:30px;width:20px;"></mdui-button-icon>
        <!--
        <mdui-chip>自动归类</mdui-chip>
        <mdui-switch unchecked-icon="remove_moderator" checked-icon="verified_user"></mdui-switch>
        -->
        <mdui-chip id="targetDir"></mdui-chip>

        <input id="selectedDirName" type="hidden" name="name" id="parent_id">
        <input id="selectedDirPath" type="hidden" name="path" id="parent_id">
        <!-- <mdui-chip id="uploadChip">点击或拖动文件到此区域上传</mdui-chip> -->
        <mdui-chip id="uploadChip" class="amdy-progress-bar">
            <div class="amdy-progress-bar-fill" style="width: 0%;"></div>
            <div class="amdy-progress-text">点击或拖动文件到此区域上传</div>
        </mdui-chip>
        <input class="mdui-textfield-input" id="uploadInput" name="file" type="file" style="display: none;" multiple >
        <mdui-button-icon type="button" id="clearBtn"  variant="text" icon="clear" onclick="clearFileInput()" style="height:30px;width:20px;"></mdui-button-icon>
        <mdui-button-icon type="button" id="uploadBtn"  variant="text" icon="arrow_circle_up" style="height:30px;width:20px;"></mdui-button-icon>
        <mdui-button-icon type="button" id="writeNote"  variant="text" icon="note_add" style="height:30px;width:20px;"></mdui-button-icon>
        <mdui-chip id="pathChip" style="width: 30%;"></mdui-chip>
        
    </from>

    <!--
    <button onclick="showDrawer()">test</button>
    -->
    <div id="fileDisplay" style="width:100%;height:700px;display: flex; justify-content: center; align-items: top;margin-top:50px;">
        <!--
        <img class="showImg" src="/extra-files/uploads/9e82106d-5b55-4c85-bd92-088bd85d0d7d.png"></img>
        -->
    </div>
    <mdui-dialog
        close-on-overlay-click
        headline="确定删除这个文件吗?"
        class="example-action"
        >
        <mdui-button slot="action" variant="text">取消</mdui-button>
        <mdui-button slot="action" variant="tonal">删除</mdui-button>
    </mdui-dialog>


{% endblock mainlay %}

{% block extjs %}
<script type="text/javascript">
    //var showImgElement = document.querySelector('.showImg');
    var fileDisplayDiv = document.getElementById('fileDisplay');
    var editView=document.getElementById("editView");
    var targetDir=document.getElementById("targetDir");
    var fileInput=document.getElementById("uploadInput");
    var selectedDirNameInput=document.getElementById("selectedDirName");
    var selectedDirPathInput=document.getElementById("selectedDirPath");
    var uploadBtn=document.getElementById("uploadBtn");
    var writeNote=document.getElementById("writeNote");
    const dialog = document.querySelector(".example-action");
    const deleteButton = dialog.querySelector('mdui-button[variant="tonal"]');
    const cancelButton = dialog.querySelector('mdui-button[variant="text"]');
    const user="{{user|safe}}";
    cancelButton.addEventListener('click', () => {
        dialog.open=false;
    })
    //设置文件夹选择的记录
    var selectedNodeId=-1;
    var selectedNode=null;
    var selectedDirName="";
    var selectedDirPath="";
    var currentDir=null;
    //设置文件选择的记录
    var selectedFileId=-1;
    var selectedFile=null;
    var selectedFileName="";
    var selectedFilePath="";
    var selectedFileType="";
    var currentFile=null;
    //设置文件最大容量
    var maxFileSize=1024*1024*100;//这里相当于100M
    const uploadChip = document.getElementById("uploadChip");
    //找到uploadChip下，类名为progress-bar-fill的div
    var uploadChipProgressBar=uploadChip.getElementsByClassName("amdy-progress-bar-fill")[0];
    //找到uploadChip下，类名为progress-bar-text的div
    var uploadChipPercentText=uploadChip.getElementsByClassName("amdy-progress-text")[0];
    console.log("uploadChipPercentText",uploadChipPercentText);
    var editor=null;
    var divElement=null;
    const pathChip = document.getElementById('pathChip');
    //保存时的event调用事件
    function tempSave(data,after){
        //after 函数在bookeditor下的1246行
        console.log("tempSave data",data," after:",after);
        updateData={"content":data['markdown'],"path":selectedFilePath,"name":selectedFileName};
        console.log("updateData:",updateData);
        apiurl='/FileManage/api/updateFile/';
        //apiurl='/FileManage/api/renameFile/';
        $.ajax({
            url:apiurl,
            type:'POST',
            data:JSON.stringify(updateData),
            contentType:'application/json;charset=utf-8',
            dataType:'json',
            success:function(response){
                console.log("/FileManage/api/updateFile/ response:",response)
                if(response.status==200){
                    aj.showTip("数据更新成功");
                    showCount(data['markdown'].length);
                }else{
                    aj.showTip("数据更新失败");
                }
            },error:function(error){
                console.log("error:".error)
            }
        })
    }

    function new_editor(path=null){
        console.log("selectedFilePath:",selectedFilePath);
        //fileDisplayDiv
        //创建一个div
        if(path==null){
            path=selectedFilePath;
        }
        fileDisplayDiv.innerHTML="";
        divElement=document.createElement("div");
        divElement.id="new_editor";
        divElement.style.width="100%";
        divElement.style.height="100%";
        divElement.style.border="1px solid #ccc"
        divElement.style.padding="10px";
        fileDisplayDiv.appendChild(divElement);
        console.log("new_editor path:<",path,"|",path,">");
        //如果传入的地址不为空，说明是服务器的文件，所以需要读取文件

        if(path!=null){
            fileUrl='/uploads/'+path
            // Assuming you have a markdown parser library (example: marked.js)
            fetch(fileUrl)
                .then(response => response.text())
                .then(data => {
                    console.log("fetchdata:",data);
                    var markdownContent = marked(data);
                    var options = {
                        wraperId: "new_editor",
                        full: true,
                        markdown: data,
                        event:{
                            save:tempSave,
                        }
                    };
                    editor = bookeditor(options);
                    //获取data的字符数量
                    var count = data.length;
                    showCount(count);
                    //fileDisplayDiv.innerHTML = `<div>${markdownContent}</div>`;
                    //添加一个按钮，点击后进入编辑页
                    //fileDisplayDiv.innerHTML += `<mdui-button-icon icon="edit" onclick="new_editor('${path}')"></mdui-button-icon>`;
                })
                .catch(error => {
                    console.error('Error fetching markdown file:', error);
                    fileDisplayDiv.innerHTML = `<p>Unable to display Markdown file.</p>`;
                });
        }else{
            var options = {
                wraperId: "new_editor",
                full: true,
                markdown: "",
                event:{
                    save:tempSave,
                }
            };
            editor = bookeditor(options);
        }
        
    }

    function showCount(count){
        console.log("showCount");
        // 获取父级 div 元素
        var parentDiv = document.getElementById('book-codemirror');
        //查找parentDiv下是否有一个countDiv的
        var countDiv = document.getElementById('countDiv');
        if(countDiv){
            countDiv.textContent = `字符数量：${count}`;
        }else{
            // 创建一个新的 div 元素
            countDiv = document.createElement('div');
            //设置newDiv的id="countDiv"
            countDiv.id = 'countDiv';
            // 设置新 div 的属性或内容
            countDiv.textContent = `字符数量：${count}`;
            // 设置countDiv的文字显示在右侧
            countDiv.style.textAlign = 'right';
            // 将新的 div 插入到父级 div 内部
            parentDiv.appendChild(countDiv);
        }
        
    }
    
    //new_editor("# 笔记 \n 从这里开始");
    
    // 添加 dragover 和 drop 事件监听器
    
    uploadChip.addEventListener('dragover', function(e) {
        e.preventDefault();
    });
    
    function triggerChangeEvent(element) {
        var event = new Event('change', { bubbles: true });
        element.dispatchEvent(event);
    }
    //文件播放到此处时，将文件保存到控件中
    uploadChip.addEventListener('drop', function(e) {
        console.log("drop");
        e.preventDefault();
        //将背景色设置成橙色
        //uploadChip.style.backgroundColor = 'orange';
        var files = e.dataTransfer.files;
        if (files.length > 0) {
            //fileInput.files = files; //把文件添加到uploadInput的files属性中
            // 将旧的文件列表和新的文件列表合并成一个数组
            var fileList = Array.from(fileInput.files).concat(Array.from(files));
            // 将数组转换成FileList对象
            var newFileList = new DataTransfer();
            // 定义一个当前文件大小的变量
            var currentFileSize = 0;
            // 遍历文件列表，将文件添加到新的FileList对象中
            fileList.forEach(function(file) {
                newFileList.items.add(file);
                //计算当前文件大小
                currentFileSize += file.size;
            });
            console.log("currentFileSize",currentFileSize);
            
            fileInput.files = newFileList.files;
            //在这里你可以触发你想要的上传操作
            console.log("files",files);
            triggerChangeEvent(fileInput);
        }
    });
    uploadBtn.addEventListener("click", function() {
        console.log("uploadBtn upload");
        aj.showLoading();
        event.preventDefault(); // 阻止表单的默认提交行为
        
        // 获取表单数据
        var formData = new FormData(editView); // 假设你有一个表单并且你知道它的 id
        console.log("formData",formData);
        var fileCount = 0;
        for (var pair of formData.entries()) {
            if (pair[0] === 'file') {
                console.log('文件名: ' + pair[1].name);
                console.log('文件大小: ' + pair[1].size);
                fileCount++;
            }
        }
        console.log('上传文件数量：' + fileCount);
        /* 
        //以下是通过xhr进行上传文件的方式，可以获取上传进度

        // 创建一个 XMLHttpRequest 对象
        const xhr = new XMLHttpRequest();
        console.log("xhr:",xhr);
        // 监听上传进度事件
        xhr.upload.addEventListener('progress', function(event) {
            if (event.lengthComputable) {
                const percentComplete = (event.loaded / event.total) * 100;
                console.log('上传进度：' + percentComplete.toFixed(2) + '%');
            }
        });

        // 监听上传完成事件
        xhr.upload.addEventListener('load', function(event) {
            console.log('文件上传完成');
        });

        // 发送请求
        xhr.open('POST', "{% url 'FileManage:api/uploadFile' %}");
        xhr.send(formData);
        */

        //以下是通过fetch进行上传文件的方式，可以获取上传进度
        // 发送表单数据
        // 监听上传进度的函数
        function listenUploadProgress(response) {
            const reader = response.body.getReader();
            const contentLength = Number(response.headers.get('Content-Length'));

            let receivedLength = 0; // 已接收的字节长度
            reader.read().then(function processResult(result) {
                if (result.done) {
                    console.log('上传完成');
                    return;
                }
                receivedLength += result.value.length;
                console.log(`已上传: ${(receivedLength / contentLength * 100).toFixed(2)}%`);
                return reader.read().then(processResult);
            });
        }

        fetch("{% url 'FileManage:api/uploadFile' %}", {
            method: 'POST',
            body: formData
        })
        .then(response => {
            // 克隆响应对象
            const responseClone = response.clone();
            listenUploadProgress(responseClone); // 调用监听上传进度的函数，并传入 response 对象
            return response.json();
        }) // 解析 JSON 响应
        .then(data => {
            //console.log("text now!");
            // 在这里处理你得到的 JSON 数据
            //const data = JSON.parse(strdata);
            console.log(data);
            aj.hideLoading();
            clearFileInput();
            if (data.status == "200") {
                aj.showTip("上传成功");
                var zTree = firstJQuery.fn.zTree.getZTreeObj("treeDemo");
                //console.log("zTree:",zTree.getNodes());
                for (var i = 0; i < data.data.length; i++) {
                    console.log("data i:",data.data[i]);
                    console.log("data.data[i].newName:",data.data[i].newName,"data.data[i].newPath:",data.data[i].newPath,data.data[i].type);
                    if(selectedNode){
                        zTree.addNodes(selectedNode, {id:(100 + i), pId:selectedNode.id, name:data.data[i].newName,path:data.data[i].newPath,type:data.data[i].type});
                    }else{
                        zTree.addNodes(null, {id:(100 + i), pId:null, name:data.data[i].newName,path:data.data[i].newPath,type:data.data[i].type});
                    }
                    
                }
                // zTree.addNodes(selectedNode, {id:(100 + newCount), pId:selectedNode.id, name:data.data.newName,path:data.data.newPath,type:data.data.type});
                //console.log("name",data.data.newName,"path",data.data.newPath);

                //zTree.addNodes(selectedNode, {id:(100 + newCount), pId:selectedNode.id, name:data.data.newName,path:data.data.newPath,type:data.data.type});
            }else{
                aj.showTip("上传失败");
            }
        })
        .catch(error => {
            // 处理请求错误
            console.error('Error:', error);
        });

        
    })


    uploadChip.addEventListener("click", function() {
        fileInput.click();
    });
    //清空fileInput
    function clearFileInput() {
        console.log("clearFileInput");
        //清空fileInput里的所有files
        fileInput.value = '';
        uploadChipPercentText.innerHTML="点击或拖动文件到此区域上传";
        uploadChipProgressBar.style.width = 0 + '%';
    }

    fileInput.addEventListener("change", function(event) {
        console.log("event:",event);
        // 处理上传文件的逻辑
        const selectedFiles = fileInput.files;
        
        if (selectedFiles.length > 0) {
            console.log("length",selectedFiles.length);
            uploadChipPercentText.innerHTML="";
            //获取当前百分比
            var currentFileSize=0;
            for(var i=0;i<selectedFiles.length;i++){
                currentFileSize+=selectedFiles[i].size;
            }
            var percent=currentFileSize/maxFileSize*100;
            //将percent转换为整数
            percent=Math.round(percent);
            console.log("percent",percent);

            //如果percent大于100，则删除最后一个文件
            if(percent>100){
                aj.showTip("文件大小超过限制,请重新选择");
                clearFileInput();
                
                
            }else{
                uploadChipProgressBar.style.width = percent + '%';
                for(var i=0;i<selectedFiles.length;i++){
                    uploadChipPercentText.innerHTML+=selectedFiles[i].name;
                    if(i<selectedFiles.length-1){
                        uploadChipPercentText.innerHTML+=",";
                    }else{
                        //显示最后一个文件在页面上
                        const showFileData=selectedFiles[i];
                        //如果是最后一个，就显示出来
                        getFileTypeUrl='/FileManage/api/getFileType/'+selectedFiles[i].name;
                        $.ajax({
                            url: getFileTypeUrl,  // 这里的URL需要根据你的Django路由配置进行修改
                            type: 'GET',
                            success: function(response) {
                                if(response.status==200){
                                    console.log("response:",response);
                                    showType=response.data.type;
                                    console.log("showType",showType);
                                    showFile(showType,showFileData,local=true);
                                    
                                    
                                }
                                
                            },
                            error: function(error) {
                                aj.showTip(error);
                                // 在控制台输出错误信息
                            }
                        })
                    }
                }
            }
            //将进度条的宽度设置为百分比
            
        }
        // 这里可以将选中的文件传递给你的上传函数进行处理或显示文件信息
        /*
        console.log("上传文件: ", selectedFile);
        console.log("上传文件路径: ", selectedFile.webkitRelativePath);
        console.log("上传文件大小: ", selectedFile.size);
        console.log("上传文件类型: ", selectedFile.type);
        console.log("上传文件最后修改时间: ", selectedFile.lastModified);
        console.log("上传文件最后修改时间: ", selectedFile.lastModifiedDate);
        console.log("上传文件名称: ", selectedFile.name);
        */

        //uploadChip.textContent = selectedFile.name;
    });
    //获取csrf
    var csrftoken = getCSRFToken();
    function getCSRFToken() {
        const csrfCookieName = 'csrftoken';
        const cookieValue = document.cookie
            .split(";")
            .find(cookie => cookie.trim().startsWith(csrfCookieName + "="));

        if (cookieValue) {
            return cookieValue
                .split('=')[1]
                .trim();
        }

        return null;
    }

    document.addEventListener('DOMContentLoaded', function() {
        document.addEventListener('paste', function(event) {
            var clipboardData = event.clipboardData || window.clipboardData;
            if(clipboardData){
                var items = clipboardData.items;
                console.log('items:', items);
                if (items) {
                    for (var i = 0; i < items.length; i++) {
                        if (items[i].type.indexOf("image") !== -1 && editor) {
                            var blob = items[i].getAsFile();
                            var reader = new FileReader();
                            reader.onload = function(event) {
                                //console.log('Pasted image:', event.target.result);
                                //showPasteFile(event.target.result);
                                uploadFile(event.target.result)
                                // 在控制台输出图片的 Data URL，你可以根据需要进行其他操作
                            };
                            reader.readAsDataURL(blob);
                        }
                    }
                }
            }
            var pastedText = clipboardData.getData('text');
            console.log('Pasted text:', pastedText);
            // 在控制台输出剪贴板内容，你可以根据需要进行其他操作
        });
    });
    //打开侧边栏快捷键
    document.addEventListener('keydown', function(event) {
        if (event.altKey && event.key === 'o') {
            console.log("alt+o");
            event.preventDefault(); // 防止默认快捷键行为
            showDrawer(); // 调用 showDrawer() 函数
        }
        if (event.altKey && event.keyCode === 122) { // F11键的keyCode是122
            event.preventDefault(); // 阻止默认行为，避免触发浏览器的全屏
            toggleFullScreen();
        }
    });
    function toggleFullScreen() {
        //var elem = document.getElementById("fileDisplayDiv");
        if (!document.fullscreenElement &&
            !document.mozFullScreenElement && !document.webkitFullscreenElement && !document.msFullscreenElement) {
            if (fileDisplayDiv.requestFullscreen) {
                fileDisplayDiv.requestFullscreen();
            } else if (fileDisplayDiv.mozRequestFullScreen) { /* Firefox */
                fileDisplayDiv.mozRequestFullScreen();
            } else if (fileDisplayDiv.webkitRequestFullscreen) { /* Chrome, Safari & Opera */
                fileDisplayDiv.webkitRequestFullscreen();
            } else if (fileDisplayDiv.msRequestFullscreen) { /* IE/Edge */
                fileDisplayDiv.msRequestFullscreen();
            }
        } else {
            if (document.exitFullscreen) {
                document.exitFullscreen();
            } else if (document.mozCancelFullScreen) { /* Firefox */
                document.mozCancelFullScreen();
            } else if (document.webkitExitFullscreen) { /* Chrome, Safari & Opera */
                document.webkitExitFullscreen();
            } else if (document.msExitFullscreen) { /* IE/Edge */
                document.msExitFullscreen();
            }
        }
    }
    //显示侧边栏
    function showDrawer(){
        console.log("showDrawer");
        navigationDrawer.open=!navigationDrawer.open;
        if(navigationDrawer.open){
            editView.style.display="block";
        }else{
            editView.style.display="none";
        }
        
    }
    //tree的设置功能
    var setting = {
        view: {
            addHoverDom: false,
            removeHoverDom: false,
            selectedMulti: false
        },
        callback:{
            onClick:onClick,
            beforeRename:beforeRename,
            beforeRemove:beforeRemove,
        },
        check: {
            enable: true
        },
        data: {
            simpleData: {
                enable: true
            }
        },
        edit: {
            enable: true
        }
    };
    //var zNodes=[{'id': 1, 'pId': 0, 'name': 'uploads', 'path': 'uploads'}, {'id': 2, 'pId': 1, 'name': '15e5c43f-ae10-4a87-bd37-f2b9188c3357.png', 'path': 'uploads\\15e5c43f-ae10-4a87-bd37-f2b9188c3357.png'}, {'id': 3, 'pId': 1, 'name': '21ae6ab1-483c-4d38-a080-dad1f12f2c04.jpg', 'path': 'uploads\\21ae6ab1-483c-4d38-a080-dad1f12f2c04.jpg'}, {'id': 4, 'pId': 1, 'name': '259eb696-8ca3-4ed7-8888-a11d84bbb123.png', 'path': 'uploads\\259eb696-8ca3-4ed7-8888-a11d84bbb123.png'}, {'id': 5, 'pId': 1, 'name': '3923268c-43fb-4586-a741-b93bc6c7bda8.png', 'path': 'uploads\\3923268c-43fb-4586-a741-b93bc6c7bda8.png'}, {'id': 6, 'pId': 1, 'name': '9e82106d-5b55-4c85-bd92-088bd85d0d7d.png', 'path': 'uploads\\9e82106d-5b55-4c85-bd92-088bd85d0d7d.png'}, {'id': 7, 'pId': 1, 'name': 'b48be958-5a5d-4129-a10c-a1df2ec8ba0e.png', 'path': 'uploads\\b48be958-5a5d-4129-a10c-a1df2ec8ba0e.png'}]
    //获取ztree数据
    var zNodes={{fileList|safe}};
    function getCSRFToken() {
        const csrfCookieName = 'csrftoken';
        const cookieValue = document.cookie
            .split(";")
            .find(cookie => cookie.trim().startsWith(csrfCookieName + "="));

        if (cookieValue) {
            return cookieValue
                .split('=')[1]
                .trim();
        }

        return null;
    }
    //初始化zTree
    $(document).ready(function(){
        console.log("document ready ")
        firstJQuery.fn.zTree.init($("#treeDemo"), setting, zNodes);
        //这里的jquery需要用新版的
        $("#addParent").bind("click", {isParent:true}, add);
        $("#writeNote").bind("click", {isParent:false,folder_type:"md"}, add);
        $.ajaxSetup({
            beforeSend: function (xhr, settings) {
                if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type) && !this.crossDomain) {
                    xhr.setRequestHeader("X-CSRFToken", getCSRFToken());
                }
            }
        });
    });

    var newCount = 1;
    function add(e) {
        console.log("add e:",e);
        var zTree = firstJQuery.fn.zTree.getZTreeObj("treeDemo");
        console.log("zTree:",zTree);
        //判断是添加文件夹还是文件
        isParent = e.data.isParent;
        folder_type=e.data.folder_type;
        nodes = zTree.getSelectedNodes();
        console.log("nodes:",nodes);
        treeNode = nodes[0];
        console.log("treeNode",treeNode);
        pId=0;
        if(treeNode){
            if(treeNode.path && treeNode.isParent){
                console.log("treeNode.path:",treeNode.path);
                pId=treeNode.id;
            }else{
                console.log("不是文件夹或没有地址");
                treeNode=null;
            }
        }else{
            console.log("没有选中的文件夹");
            treeNode=null;
        }


        //如果有被选中的node，则在此节点下添加node
        if (treeNode) {
            console.log("addChildNode");
            console.log("treeNode.path:",treeNode.path);
            inputPath=treeNode.path;
        } else {
            console.log("addParentNode");
            inputPath=null;
        }
        newFolder(inputPath,"new node" + newCount,treeNode,pId,zTree,folder_type)

        
    };
    function beforeRemove(treeId,treeNode){
        console.log("beforeRemove:",treeId,'--',treeNode.path,'--',treeNode.name);
        //修改文件夹名称前的服务器操作
        
        //apiurl='/FileManage/api/renameFile/';
        dialog.open=true
        deleteButton.addEventListener('click', function () {
            dialog.open=false;
            console.log("click delete",treeNode.path,treeNode.name);
            data={path:treeNode.path,name:treeNode.name};
            apiurl='/FileManage/api/deleteFile/';
            $.ajax({
                url:apiurl,
                type:'POST',
                data:JSON.stringify(data),
                contentType:'application/json;charset=utf-8',
                dataType:'json',
                success:function(response){
                    console.log("/FileManage/api/deleteFile/ response:",response)
                    if(response.status==200){
                        var zTree = firstJQuery.fn.zTree.getZTreeObj("treeDemo");
                        zTree.removeNode(treeNode,false);
                        aj.showTip("删除成功");
                    }else{
                        aj.showTip("不可删除");
                    }
                },error:function(error){
                    console.log("error:".error)
                }
            })
        })
        /*
        
        */
        return false;

    }
    //修改文件夹名称后的服务器操作
    function beforeRename(treeId,treeNode,newName,isCancel){
        console.log("beforeRename:",treeId,'--',treeNode.path,'--',treeNode.name,'--',newName);
        data={path:treeNode.path,name:treeNode.name,newName:newName};
        apiurl='/FileManage/api/renameFile/';
        var oldName=treeNode.name
        //console.log("csrftoken:",csrftoken);//6knzkFIRL3NWYM4Ev80EMPZFYzcvvNRN
        $.ajax({
            url: apiurl,
            type: 'POST',
            data: JSON.stringify(data),
            contentType: 'application/json;charset=utf-8', // 根据你的API接口要求的Content-Type进行设置
            dataType: 'json',
            success: function (response) {
                // success callback
                console.log("/FileManage/api/renameFile/ get:",response);
                if(response.status==200){
                    aj.showTip("修改成功");
                    treeNode.path=response.data.path;
                }else{
                    aj.showTip("修改失败");
                    var zTree = firstJQuery.fn.zTree.getZTreeObj("treeDemo");
                    zTree.editName(treeNode);
                    zTree.cancelEditName(oldName);
                }
            },
            error: function (error) {
                // error callback
                console.log("error:",error);
            }
        });
    }
    function newFolder(path,name,treeNode,pId,zTree,folder_type,folder_content=""){
        console.log("newFolder");
        //var csrftoken = getCSRFToken();
        //console.log("csrftoken:",csrftoken);
        if(folder_type=="md"){
            isParent=false
        }else{
            isParent=true
        }
        data={path:path,name:name,folder_type:folder_type};
        console.log("data:",data);
        console.log("JSON.stringify(data):",JSON.stringify(data));
        //console.log(data);
        //ajaxSetup();
        //console.log(data);
        apiurl='/FileManage/api/addFolder/';
        //console.log("csrftoken:",csrftoken);//6knzkFIRL3NWYM4Ev80EMPZFYzcvvNRN
        $.ajax({
            url: apiurl,
            type: 'POST',
            data: JSON.stringify(data),
            contentType: 'application/json;charset=utf-8', // 根据你的API接口要求的Content-Type进行设置
            dataType: 'json',
            success: function (response) {
                // success callback
                console.log("/FileManage/api/addFolder/ get:",response);
                if(response.status==200){
                    if(folder_type=="md"){
                        zTreeNodeType="md"
                    }else{
                        zTreeNodeType="dir"
                    }
                    treeNode = zTree.addNodes(treeNode, {id:(100 + newCount), pId:pId, isParent:isParent, name:response.data.name,path:response.data.path,type:zTreeNodeType});
                    if (treeNode) {
                        zTree.editName(treeNode[0]);
                    } else {
                        alert("叶子节点被锁定，无法增加子节点");
                    }
                }
            },
            error: function (error) {
                // error callback
                console.log("error:",error);
            }
        });
    }
    //点击事件
    function onClick(event,treeId,treeNode,clickFlag){
        console.log("event:",event);
        console.log("treeId:",treeId);
        console.log("treeNode:",treeNode);
        console.log("clickFlag:",clickFlag);
        console.log("isParent:",treeNode.isParent);
        console.log("type:",treeNode.type);
        console.log("selectedNodeId",selectedNodeId);
        var zTree = firstJQuery.fn.zTree.getZTreeObj("treeDemo");
        if(selectedNodeId==treeNode.id){
            console.log("取消选择状态");
            zTree.cancelSelectedNode(treeNode);
            //清空选中的节点
            fileDisplayDiv.innerHTML="";
            console.log("已清空");
            selectedNodeId=-1;
        }else{
            console.log("selectedNodeId:",selectedNodeId,"treeNode.id:",treeNode.id);
            selectedNodeId=treeNode.id;
            //如果选中的是文件夹，那么就保存其名称和地址
            if(treeNode.type=="dir"){
                selectedNode=treeNode;
                selectedDirName=treeNode.name;
                selectedDirPath=treeNode.path;
                selectedDirNameInput.value=treeNode.name;
                selectedDirPathInput.value=treeNode.path;
                targetDir.textContent=selectedDirName;

                console.log("selectedDirName:",selectedDirName,"selectedDirPath:",selectedDirPath);
                //清空显示的div
                fileDisplayDiv.innerHTML="";
            }else{//如果选中的是文件
                selectedFile=treeNode;
                selectedFileName=treeNode.name;
                selectedFilePath=treeNode.path;
                selectedFileId=treeNode.id;
                console.log("selectedFileName:",selectedFileName,"selectedFilePath:",selectedFilePath)
                showFile(treeNode.type,treeNode.path);
            }
        }
        
        
        //showImgElement.src="/extra-files/"+treeNode.path;
        

    }
    //显示粘贴的图片 用于测试，有效
    /*
    function showPasteFile(data){
        console.log("showPasteFile:");
        fileDisplayDiv.innerHTML=`<img src="${data}" style="max-width: 100%; max-height: 100%;">`;
    }
    */
    //剪贴板数据转上传数据
    function dataURLToBlob(dataURL) {
        var parts = dataURL.split(';base64,');
        var contentType = parts[0].split(':')[1];
        var raw = window.atob(parts[1]);
        var rawLength = raw.length;
        var uInt8Array = new Uint8Array(rawLength);

        for (var i = 0; i < rawLength; ++i) {
            uInt8Array[i] = raw.charCodeAt(i);
        }

        return new Blob([uInt8Array], { type: contentType });
    }
    //上传文件
    function uploadFile(data) {
        // 创建 FormData 对象
        var formData = new FormData();
        // 将图片 Data URL 转换为 Blob 对象
        var blob = dataURLToBlob(data);
        console.log("blob.type:",blob.type);
        //获取blob.type的后缀名
        var suffix = blob.type.split('/')[1];
        console.log("suffix:",suffix);
        //获取当前的时间的时间戳
        var timestamp = new Date().getTime();
        //将时间戳转为字符串
        var timestampStr = timestamp.toString();
        //获取当前用户名
        console.log("name:",user+timestampStr+"."+suffix);
        // 添加文件到 FormData 对象
        formData.append('file', blob, user+timestampStr+"."+suffix);
        //在formData中添加name和path字段
        formData.append('name', selectedDirName);
        formData.append('path', "mdImage");
        postUrl="/FileManage/api/uploadFile/";
        // 发送 AJAX 请求
        var xhr = new XMLHttpRequest();
        xhr.open('POST', postUrl, true);
        xhr.setRequestHeader('X-CSRFToken', getCSRFToken());
        xhr.onload = function () {
            if (xhr.status === 200) {
                console.log("xhr",xhr.response);
                //将xhr.response的字符串转为json
                var response = JSON.parse(xhr.response);
                console.log("response",response);
                console.log("file Name:",response.data[0].newName,response.data[0].newPath)
                //查看当前网站的地址
                console.log("current url:",window.location.href);
                url=window.location.href;
                //当前url=http://127.0.0.1/FileManage/
                //替换FileManage为extra-files
                url=url.replace("FileManage","uploads");
                console.log("new url:",url);
                //调用editor的image功能
                c = "![{0}]({1})".format(response.data[0].newName, url+response.data[0].newPath);
                console.log("html=>editor:",editor);
                editor.toolbar.editor.editor.replaceSelection(c);

                console.log('File uploaded successfully.');
            } else {
                console.error('File upload failed.');
            }
        };
        xhr.send(formData);
    }

    function showFile(type,path,local=false){
        switch (type) {
            case 'image':
                if(local==false){
                    //将fileDisplayDiv.innerHTML设置为一个label，label中包含path的值，然后旁边加上一个按钮，名称为"复制地址",点击按钮即可复制地址
                    //fileDisplayDiv.innerHTML = `<div><label>${path}</label><button onclick="copyText('${path}')">复制地址</button></div>`
                    //使fileDsiplayDiv中添加换行
                    //将fileDisplayDiv.innerHTML设置为一个img，img的src为path
                    pathChip.style.display = 'block';
                    pathChip.innerHTML = "/uploads/"+path;
                    pathChip.onclick = function () {
                        //将pathChip的内容复制到电脑的剪贴板


                        navigator.clipboard.writeText(pathChip.innerHTML).then(function () {
                            console.log('Text copied to clipboard');
                            aj.showTip("复制成功");
                        }).catch(function (err) {
                            console.error('Could not copy text: ', err);
                            aj.showTip("没有复制成功");
                        });
                    };
                    
                    
                    fileDisplayDiv.innerHTML = `<img src="/uploads/${path}" style="max-width: 100%; max-height: 100%;">`
                }else{
                    pathChip.style.display = 'none';
                    // 创建一个 FileReader 对象
                    var reader = new FileReader();

                    // 读取图片文件，并在读取完成后触发回调函数
                    reader.onload = function(e) {
                    // 将读取到的图片数据设置为 mdui-avatar 元素的 src
                        fileDisplayDiv.innerHTML = `<img src="${e.target.result}" style="max-width: 100%; max-height: 100%;">`;
                    };
                    reader.readAsDataURL(path);
                    //reader.readAsText(path);
                    
                }
                
                break;
            case 'pdf':
                pathChip.style.display = 'none';
                if(local==false){
                    fileDisplayDiv.innerHTML = `<embed src="/uploads/${path}" type="application/pdf" style="width:100%;height:100%;">`;
                }else{
                    var reader = new FileReader();
                    // 读取图片文件，并在读取完成后触发回调函数
                    reader.onload = function(e) {
                        console.log("reader:",e.target.result);
                    // 将读取到的图片数据设置为 mdui-avatar 元素的 src
                        fileDisplayDiv.innerHTML = `<embed src="${e.target.result}" type="application/pdf" style="width:100%;height:100%;">`;
                    };
                    reader.readAsDataURL(path);
                    //fileDisplayDiv.innerHTML = `<embed src="${path}" type="application/pdf" style="width:100%;height:100%;">`;
                }
              
                break;
            case 'md':
                pathChip.style.display = 'none';
                if(local==false){
                    fileUrl='/uploads/'+path
                    console.log("fileUrl:",fileUrl);
                    // Assuming you have a markdown parser library (example: marked.js)
                    fetch(fileUrl)
                        .then(response => response.text())
                        .then(data => {
                            console.log("fetchdata:",data);
                            var markdownContent = marked(data);
                            fileDisplayDiv.innerHTML = `<div>${markdownContent}</div>`;
                            //添加一个按钮，点击后进入编辑页
                            fileDisplayDiv.innerHTML += `<mdui-button-icon icon="edit" onclick="new_editor()"></mdui-button-icon>`;
                        })
                        .catch(error => {
                            console.error('Error fetching markdown file:', error);
                            fileDisplayDiv.innerHTML = `<p>Unable to display Markdown file.</p>`;
                        });
                }else{
                    console.log("readerdata:",path);
                    
                    var reader = new FileReader();
                    // 读取图片文件，并在读取完成后触发回调函数
                    reader.onload = function(e) {
                        console.log("reader:",e.target.result);
                        var htmlContent = marked(e.target.result);
                        fileDisplayDiv.innerHTML =htmlContent;
                        
                    // 将读取到的图片数据设置为 mdui-avatar 元素的 src
                        //fileDisplayDiv.innerHTML = `<embed src="${e.target.result}" type="application/pdf" style="width:100%;height:100%;">`;
                    };
                    reader.readAsText(path);
                }
              
                break;
            case 'text':
                pathChip.style.display = 'none';
                if(local==false){
                    fileUrl='/uploads/'+path
                    // Assuming direct file display without parsing
                    fetch(fileUrl)
                        .then(response => response.text())
                        .then(data => {
                            fileDisplayDiv.innerHTML = `<pre>${data}</pre>`;
                        })
                        .catch(error => {
                            console.error('Error fetching text file:', error);
                            fileDisplayDiv.innerHTML = `<p>Unable to display text file.</p>`;
                        });
                }else{
                    var reader = new FileReader();
                    reader.onload = function(e) {
                        fileDisplayDiv.innerHTML = `<pre>${e.target.result}</pre>`;
                    };
                    reader.readAsText(path);
                }
                
              break;
            case 'doc':
                pathChip.style.display = 'none';
                fileDisplayDiv.innerHTML = '<p>word文档暂时无法显示</p>';
                break;
            case "python":
                pathChip.style.display = 'none';
                if(local==false){
                    fileUrl='/uploads/'+path
                    fetch(fileUrl)
                    .then(response => response.text())
                    .then(data => {
                        fileDisplayDiv.innerHTML = '<pre><code class="python">' + data + '</code></pre>';
                        hljs.highlightAll();
                    })
                    .catch(error => {
                    console.log("Error fetching file:", error);
                    });
                }else{
                    var reader = new FileReader();
                    reader.onload = function(e) {
                        fileDisplayDiv.innerHTML = '<pre><code class="python">' + e.target.result + '</code></pre>';
                        hljs.highlightAll();
                    };
                    reader.readAsText(path);
                }
                
              break;
            case "audio":
                pathChip.style.display = 'none';
                if(local==false){
                    fileUrl='/uploads/'+path
                    // 创建音频元素
                    const audioElement = document.createElement("audio");
                    audioElement.src = fileUrl;
                    audioElement.controls = true;
                    fileDisplayDiv.innerHTML='';
                    fileDisplayDiv.appendChild(audioElement);
                }else{
                    var reader = new FileReader();
                    reader.onload = function(e) {
                        const audioElement = document.createElement("audio");
                        audioElement.src = e.target.result;
                        audioElement.controls = true;
                        fileDisplayDiv.innerHTML='';
                        fileDisplayDiv.appendChild(audioElement);
                    };
                    reader.readAsDataURL(path);
                }
                

                break;
            case "video":
                pathChip.style.display = 'none';
                if(local==false){
                    fileUrl='/uploads/'+path
                    // 创建视频元素
                    const videoElement = document.createElement("video");
                    videoElement.src = fileUrl;
                    videoElement.controls = true;
                    videoElement.style.maxWidth = "100%"; // 设置最大宽度为100%
                    videoElement.style.maxHeight = "100%"; // 设置最大高度为100%
                    fileDisplayDiv.innerHTML='';
                    fileDisplayDiv.appendChild(videoElement);
                }else{
                    var reader = new FileReader();
                    reader.onload = function(e) {
                        const videoElement = document.createElement("video");
                    videoElement.src = e.target.result;
                    videoElement.controls = true;
                    videoElement.style.maxWidth = "100%"; // 设置最大宽度为100%
                    videoElement.style.maxHeight = "100%"; // 设置最大高度为100%
                    fileDisplayDiv.innerHTML='';
                    fileDisplayDiv.appendChild(videoElement);
                    };
                    reader.readAsDataURL(path);
                }
                
                break;
            default:
                pathChip.style.display = 'none';
                fileDisplayDiv.innerHTML = `<p>暂不支持预览的文件</p>`;
                break;
        }
    }
    //增加编辑功能 增加/修改/删除  暂时取消此功能，因为不需要在树中添加文件
    function addHoverDom(treeId, treeNode) {
        var sObj = $("#" + treeNode.tId + "_span");
        if (treeNode.editNameFlag || $("#addBtn_"+treeNode.tId).length>0) return;
        var addStr = "<span class='button add' id='addBtn_" + treeNode.tId
            + "' title='add node' onfocus='this.blur();'></span>";
        sObj.after(addStr);
        var btn = $("#addBtn_"+treeNode.tId);
        if (btn) btn.bind("click", function(){
            var zTree = firstJQuery.fn.zTree.getZTreeObj("treeDemo");
            zTree.addNodes(treeNode, {id:(100 + newCount), pId:treeNode.id, name:"new node" + (newCount++)});
            return false;
        });
    };
    function removeHoverDom(treeId, treeNode) { //暂时取消此功能，因为不需要在树中添加文件
        $("#addBtn_"+treeNode.tId).unbind().remove();
    };
</SCRIPT>
{% endblock extjs %}
